package com.lwq.im.chartdemo.config;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lwq.im.chartdemo.bean.InitBean;
import com.lwq.im.chartdemo.bean.RequestBody;
import com.lwq.im.chartdemo.config.propperties.ChartProperties;
import com.lwq.im.chartdemo.handler.ChartRequestHandler;
import com.lwq.im.chartdemo.handler.SocketChartHandler;
import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class ChartConfig implements ChartRequestHandler, ApplicationListener<ApplicationStartedEvent> {



    @Autowired
    private ApplicationContext applicationContext;


    private  ConcurrentHashMap<String,ChartRequestHandler> requestHandlerMap = new ConcurrentHashMap<>();

    @Bean(destroyMethod = "destroy")
    public SocketChartHandler getSocketChartHandler(ChartProperties chartProperties){
        InitBean initBean = InitBean.builder().port(chartProperties.getPort())
                .writeIdle(chartProperties.getWriteIdle())
                .readIdle(chartProperties.getReadIdle())
                .chartRequestHandler(this)
                .build();
        SocketChartHandler socketChartHandler = new SocketChartHandler(initBean);
        return socketChartHandler;
    }

    @Override
    public String getOpType() {
        return null;
    }

    @Override
    public void doHandle(Channel channel, RequestBody requestBody) {

        String opType = requestBody.getOpType();
        if (StrUtil.isBlank(opType)){
            return;
        }

        ChartRequestHandler chartRequestHandler = requestHandlerMap.get(opType);
        if (ObjectUtil.isNull(chartRequestHandler)){
            return;
        }

        chartRequestHandler.doHandle(channel, requestBody);
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        Map<String, ChartRequestHandler> beansOfType = applicationContext.getBeansOfType(ChartRequestHandler.class);
        if (CollectionUtil.isNotEmpty(beansOfType)){
            for(Map.Entry<String,ChartRequestHandler> entry : beansOfType.entrySet()){
                ChartRequestHandler value = entry.getValue();
                String opType = value.getOpType();
                if(StrUtil.isNotBlank(opType)){
                    requestHandlerMap.put(opType, value);
                }
            }
        }

        SocketChartHandler socketChartHandler = applicationContext.getBean(SocketChartHandler.class);
        socketChartHandler.start();
    }
}
